package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import dao.BaseDao;
import dao.OrderDao;
import entity.Order;

public class OrderDaoImpl extends BaseDao implements OrderDao{
	
	private Connection conn=null;
	private PreparedStatement pstmt=null;
	private ResultSet rs=null;

	@Override
	public int add(Order order) {
		int result=0;
		try {
			conn=super.getConnection();
			String sql="insert into `order`(orderNo,`subject`,phone,amount,body,`status`,patType,trade_no) values(?,?,?,?,?,?,?,?)";
			
			pstmt=conn.prepareStatement(sql);
			
			pstmt.setObject(1, order.getOrderNO());
			pstmt.setObject(2, order.getSubject());
			pstmt.setObject(3, order.getPhone());
			pstmt.setObject(4, order.getAmount());
			pstmt.setObject(5, order.getBody());
			pstmt.setObject(6, order.getStatus());
			pstmt.setObject(7, order.getPayType());
			pstmt.setObject(8, order.getTrade_no());
			
			
			
			result=pstmt.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			super.closeAll(conn, pstmt, rs);
		}
		return result;
	}

	@Override
	public Order findOrderNo(String orderNo) {
		Order order=null;
		try {
			conn=super.getConnection();
			String sql="select * from `order` where orderNo=?";
			pstmt=conn.prepareStatement(sql);
			
			pstmt.setObject(1, orderNo);
			
			rs=pstmt.executeQuery();
			while (rs.next()) {
				order=new Order();
				order.setAmount(rs.getDouble("amount"));
				order.setBody(rs.getString("body"));
				order.setId(rs.getInt("id"));
				order.setOrderNO(rs.getString("orderNO"));
				order.setPayType(rs.getInt("patType"));
				order.setPhone(rs.getString("phone"));
				order.setStatus(rs.getInt("status"));
				order.setSubject(rs.getString("subject"));
				order.setTrade_no(rs.getString("trade_no"));
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			super.closeAll(conn, pstmt, rs);
		}
		return order;
	}

	@Override
	public int update(Order order) {
		int result=0;
		try {
			conn=super.getConnection();
			String sql="update `order` set `status`=?,patType=?,trade_no=? where orderNo=?";
			pstmt=conn.prepareStatement(sql);
			
			pstmt.setObject(1, order.getStatus());
			pstmt.setObject(2, order.getPayType());
			pstmt.setObject(3, order.getTrade_no());
			pstmt.setObject(4, order.getOrderNO());
			
			result=pstmt.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			super.closeAll(conn, pstmt, rs);
		}
		return result;
	}

}
